<template>
    <el-dialog :title="'写入源'" :visible.sync="dialogJSFormVisible" :append-to-body="true" :close-on-click-modal="false" :before-close="handleBeforeClose">
      <el-form label-position="right" label-width="150px" :model="writerForm" :rules="rules">
        <el-form-item label="数据库源：" prop="sourceId" label-width="150px">
          <el-select v-model="writerForm.sourceId" filterable @change="rDsChange">
            <el-option v-for="item in rDsList" :key="item.id" :label="item.sourceName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据存储：">
          <el-select v-model="writerForm.increment" filterable @change="changeType">
            <el-option v-for="item in dictList('data_get_is_increment')" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据更新方式：">
          <el-select v-model="writerForm.incrementUpdateStyle" filterable @change="handleSelectChange">
            <el-option v-for="item in dictList('data_update_method')" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!--      合并配置-->
        <el-form-item label="更新配置：" v-if="writerForm.incrementUpdateStyle === '1'">
          <el-col :span="24" style="border: 1px dashed #bbb; margin-left: 20px">
            <el-table :data="selColumnList" style="width: 100%">
              <!-- 表格列配置 -->
              <el-table-column label="id" prop="id" :editable="true" v-if="false">
                <template slot-scope="scope">
                  <!-- 使用 el-input 进行编辑 -->
                  <el-input v-model="scope.row.id" @blur="handleEdit(scope.row, 'name')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="tableName" label="表名" width="180"> </el-table-column>
              <el-table-column label="表描述" prop="tableComment" :editable="true" v-if="false">
                <template slot-scope="scope">
                  <!-- 使用 el-input 进行编辑 -->
                  <el-input v-model="scope.row.tableComment"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="唯一字段" prop="tableComment">
                <template slot-scope="scope">
                  <!-- 使用 el-input 进行编辑 -->
                  <!--                    <el-input v-model="scope.row.tableComment" @blur="handleEdit(scope.row, 'age')"></el-input>-->
                  <el-select v-model="scope.row.margeOnlyColumn" placeholder="请选择唯一字段">
                    <el-option v-for="item in scope.row.columnList" :key="item.columnName" :label="item.columnComment" :value="item.columnName" :disabled="item.disabled"> </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <!-- 其他列配置 -->
            </el-table>
          </el-col>
        </el-form-item>
  
        <!--      更新配置-->
        <el-form-item label="更新配置：" v-if="writerForm.incrementUpdateStyle === '0'">
          <el-col :span="24" style="border: 1px dashed #bbb">
            <el-table :data="selColumnList" @row-click="handleRowClick">
              <!-- 表格列配置 -->
              <el-table-column label="id" prop="id" :editable="true" v-if="false">
                <template slot-scope="scope">
                  <!-- 使用 el-input 进行编辑 -->
                  <el-input v-model="scope.row.id" @blur="handleEdit(scope.row, 'name')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="tableName" label="表名" width="380"> </el-table-column>
              <el-table-column label="表描述" prop="tableComment" :editable="true" v-if="false">
                <template slot-scope="scope">
                  <!-- 使用 el-input 进行编辑 -->
                  <el-input v-model="scope.row.tableComment"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="更新范围" prop="tableComment">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.replaceStyle" @change="handleRadioChange">
                    <el-radio :label="0">整表</el-radio>
                    <el-radio :label="1">按时间</el-radio>
                    <el-radio :label="2">自定义</el-radio>
                  </el-radio-group>
                  <el-dialog title="设置时间段" :visible.sync="dialogFormVisible" :append-to-body="true" :close-on-click-modal="false">
                    <el-form :model="selColumnList[nowIndex]">
                      <el-form-item label="时间字段" label-width="100px" label-position="left">
                        <el-select v-model="selColumnList[nowIndex].margeDateColumn" placeholder="请选择时间字段" :style="{ width: '400px' }">
                          <el-option v-for="item in selColumnList[nowIndex].columnList" :key="item.columnName" :label="item.columnComment" :value="item.columnName" :disabled="item.disabled">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="筛选时段" label-width="100px" label-position="left">
                        <el-date-picker
                          @change="handleDateRangeChange"
                          :style="{ width: '400px' }"
                          v-model="selColumnList[nowIndex].margeDateRange"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                        >
                        </el-date-picker>
                      </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                      <el-button @click="dialogFormVisible = false">取 消</el-button>
                      <el-button type="primary" @click="addTj(selColumnList[nowIndex], scope.$index)">确 定</el-button>
                    </div>
                  </el-dialog>
  
                  <el-dialog title="自定义合并" :visible.sync="dialogFormVisibleForYou" :append-to-body="true" :close-on-click-modal="false">
                    <el-form :model="scope.row.sql">
                      <el-form-item label="输入sql" label-width="100px" label-position="left">
                        <el-input type="textarea" v-model="scope.row.writerSql"></el-input>
                      </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                      <el-button @click="dialogFormVisibleForYou = false">取 消</el-button>
                      <el-button type="primary" @click="addTjSql(scope.row, scope.$index)">确 定</el-button>
                    </div>
                  </el-dialog>
                  <!--                <el-radio-group  @change="handleReplaceStyleChange">-->
                  <!--                  <el-radio   :label="1":checked="scope.row.replaceStyle === '1'"  @click="changeValueforList(scope.row,'1',scope.$index)">整表{{scope.row.replaceStyle}}</el-radio>-->
                  <!--                  <el-popover-->
                  <!--                    placement="top-start"-->
                  <!--                    title=""-->
                  <!--                    trigger="click"-->
                  <!--                    content="设置按时间更新">-->
                  <!--                    <el-form-item label="时间字段" label-width="100px" label-position="left">-->
                  <!--                      <el-select v-model="scope.row.onlyColumn" placeholder="请选择时间字段">-->
                  <!--                        <el-option-->
                  <!--                          v-for="item in scope.row.columnList"-->
                  <!--                          :key="item.columnName"-->
                  <!--                          :label="item.columnComment"-->
                  <!--                          :value="item.columnName"-->
                  <!--                          :disabled="item.disabled">-->
                  <!--                        </el-option>-->
                  <!--                      </el-select>-->
                  <!--                    </el-form-item>-->
                  <!--                    <el-form-item label="筛选时段" label-width="100px" label-position="left">-->
                  <!--                      <el-date-picker @change="handleDateRangeChange"-->
                  <!--                                      v-model="dateRange"-->
                  <!--                                      type="datetimerange"-->
                  <!--                                      range-separator="至"-->
                  <!--                                      start-placeholder="开始日期"-->
                  <!--                                      end-placeholder="结束日期">-->
                  <!--                      </el-date-picker>-->
                  <!--                    </el-form-item>-->
                  <!--                    <button @click="changeValueforList(scope.row,'2',scope.$index)" style="background-color: transparent;border: none;" slot="reference">-->
                  <!--                      <el-radio  :label="2" :checked="scope.row.replaceStyle === '2'">按时间</el-radio>-->
                  <!--                    </button>-->
                  <!--                  </el-popover>-->
                  <!--                  <el-popover-->
                  <!--                    placement="top-start"-->
                  <!--                    title=""-->
                  <!--                    width="300"-->
                  <!--                    trigger="click"-->
                  <!--                    content="输入sql">-->
                  <!--                    <el-form-item >-->
                  <!--                      <el-input type="textarea" v-model="scope.row.writerSql"></el-input>-->
                  <!--                    </el-form-item>-->
                  <!--                    <button @click="changeValueforList(scope.row,'3',scope.$index)" style="background-color: transparent;border: none;" slot="reference">-->
                  <!--                      <el-radio   :label="3" :checked="scope.row.replaceStyle === '3'">自定义</el-radio>-->
                  <!--                    </button>-->
                  <!--                  </el-popover>-->
                  <!--                </el-radio-group>-->
                </template>
                <!--              <template slot-scope="scope">-->
                <!--                &lt;!&ndash; 使用 el-input 进行编辑 &ndash;&gt;-->
                <!--                &lt;!&ndash;                    <el-input v-model="scope.row.tableComment" @blur="handleEdit(scope.row, 'age')"></el-input>&ndash;&gt;-->
                <!--                <el-select v-model="scope.row.onlyColumn" placeholder="请选择唯一字段" @change="handleSelectChange(scope.row)">-->
                <!--                  <el-option-->
                <!--                    v-for="item in scope.row.columnList"-->
                <!--                    :key="item.columnName"-->
                <!--                    :label="item.columnComment"-->
                <!--                    :value="item.columnName"-->
                <!--                    :disabled="item.disabled">-->
                <!--                  </el-option>-->
                <!--                </el-select>-->
                <!--              </template>-->
              </el-table-column>
              <!-- 其他列配置 -->
            </el-table>
          </el-col>
        </el-form-item>
        
      </el-form>
      <!--    <el-button  type="primary" style="margin-top: 12px;margin-bottom: 12px;"-->
      <!--                @click="createJSJob">提交</el-button>-->
      <el-row type="flex" justify="center" align="right">
        <el-button type="primary" style="width: 15%; margin-top: 5%" @click="createJSJob">提交</el-button>
      </el-row>
    </el-dialog>
  </template>
  
  <script>
  import { listDataSource } from '@/api/metadata/sqlconsole'
  import { getTableList } from '@/api/masterdata/masterdataTable'
  import { fetchcolumnList } from '@/api/metadata/column'
  import Bus from '../busWriter'
  export default {
    name: 'TableWriter',
    // props: ['writerInfo','readerInfo'],
    props: {
      writerInfo: {},
      readerInfo: {},
    },
    data() {
      return {
        dateRange: [],
        dialogJSFormVisible: true,
        dialogFormVisible: false,
        dialogFormVisibleForYou: false,
        jdbcDsQuery: {
          current: 1,
          size: 200,
          ascs: 'datasource_name',
        },
        wDsList: [],
        schemaList: [],
        rDsList: [],
        wColumnList: [],
        columns: [],
        fromTableName: '',
        wTbList: [],
        dataSource: '',
        createTableName: '',
        writerForm: {
          sourceId: '',
          increment: '1',
          incrementUpdateStyle: 'insert',
          selColumnList: [],
        },
        // readerForm: this.getReaderData(),
        rules: {
          targetDatasourceId: [{ required: true, message: '数据库源为必填项', trigger: 'change' }],
          tableName: [{ required: true, message: 'this is required', trigger: 'change' }],
        },
        key: '',
        selColumnList: [],
        nowIndex: 0,
      }
    },
    created() {
      console.log('得到的回传信息' + JSON.stringify(this.readerInfo))
  
      this.selColumnList = this.readerInfo.tableId
      this.writerForm = this.writerInfo
      // if(!this.writerInfo.increment){
      //   this.writerForm.increment = '1'
      // }
      // if(!this.writerInfo.incrementUpdateStyle){
      //   this.writerForm.incrementUpdateStyle = 'insert'
      // }
      this.getJdbcDs()
    },
    methods: {
      // rDsChange(e) {
      //   // 清空
      //   this.writerForm.sourceName = ''
      //   this.writerForm.sourceId = e
      //   this.rDsList.find((item) => {
      //     if (item.id === e) {
      //       this.writerForm.sourceName=item.sourceName
      //     }
      //   })
      // },
      addTj(row, index) {
        var onlyColumn = row.onlyColumn
        var dateRange = row.margeDateRange
        this.selColumnList[this.nowIndex].margeOnlyColumn = onlyColumn
        this.selColumnList[this.nowIndex].margeDateRange = dateRange
        this.selColumnList[this.nowIndex].writeStime = dateRange[0]
        this.selColumnList[this.nowIndex].writeEtime = dateRange[1]
        console.log('选中的值唯一:========' + onlyColumn)
        console.log('选中的值时间:========' + JSON.stringify(this.selColumnList))
        // alert(index);
        this.dialogFormVisible = false
      },
      addTjSql(row, index) {
        var sql = row.writerSql
  
        this.selColumnList[this.nowIndex].writerSql = sql
        console.log('选中的值时间:========' + JSON.stringify(this.selColumnList))
        // alert(index);
        this.dialogFormVisibleForYou = false
      },
      handleRadioChange(value) {
        // 当选项变化时触发
        console.log('选中的值:', value)
        this.selColumnList[this.nowIndex].replaceStyle = value
        if (value == 1) {
          this.dialogFormVisible = true
        }
        if (value == 2) {
          this.dialogFormVisibleForYou = true
        }
      },
      changeValueforList(row, val, index) {
        // alert(index)
        this.selColumnList[index].replaceStyle = val
        row.replaceStyle = val
      },
      handleReplaceStyleChange(value) {
        console.log('选项发生变化，新的值为：', value)
      },
      handleDateRangeChange() {
        // 处理日期范围选择器的值变化事件
        if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
          this.readerForm.effectTime = this.dateRange[0]
          this.readerForm.failureTime = this.dateRange[1]
          console.log('开始日期:', this.startDate)
          console.log('结束日期:', this.endDate)
        } else {
          this.startDate = ''
          this.endDate = ''
        }
      },
      handleBeforeClose(done) {
        this.createJSJob()
      },
      createJSJob() {
        this.dialogJSFormVisible = false
        this.writerForm.selColumnList = this.selColumnList
        this.$emit('change', this.writerForm)
      },
      //获取列名
      rTbChange(id) {
        this.wTbList.forEach((item) => {
          if (item.id == id) {
            this.writerForm.tableName = item.tableName
          }
        })
        fetchcolumnList({ sourceId: id }).then((res) => {
          if (res.data.code === 0) {
            this.wColumnList = res.data.data
          } else {
            this.$message.error(res.data.msg)
          }
        })
      },
      rest() {
        this.wColumnList = []
        this.wTbList = []
        this.writerForm = {
          sourceId: undefined,
          tableId: '',
          tableName: '',
          checkAll: false,
          isIndeterminate: true,
          tableSchema: '',
          status: 'false',
          sourceName: undefined,
          preSql: '', //前置sql语句
          postSql: '',
          columns: [],
        }
      },
      handleSelectChange(value) {
        // 处理 el-select 的选项变化事件
        console.log('选中的选项:', value)
        // this.selColumnList[this.nowIndex].margeOnlyColumn = value
        // this.writerForm.incrementUpdateStyle = value
        // 在这里可以执行其他操作
      },
      //选择是否创建表
      changeType(e) {
        this.key = e
        console.log(this.readerInfo, 'readerInfo===========')
        if (e == 'true') {
          this.wColumnList = this.readerInfo.columns
          this.writerForm.tableId = this.readerInfo.tableId
          this.writerForm.tableName = this.readerInfo.tableName
        } else {
          getTableList({ sourceId: this.writerForm.targetDatasourceId }).then((res) => {
            if (res.data.code === 200) {
              this.wTbList = res.data.data
            }
          })
          this.wColumnList = []
          // 获取可用表
          if (this.writerForm.tableId) {
            fetchcolumnList({ sourceId: this.writerForm.tableId }).then((res) => {
              if (res.data.code === 0) {
                this.wColumnList = res.data.data
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }
        }
      },
      // 获取可用数据源
      getJdbcDs() {
        this.loading = true
        listDataSource().then((response) => {
          this.rDsList = response.data.data
          this.loading = false
        })
      },
      // 获取表名
      getTables(type) {
        getTableList({ sourceId: this.writerForm.targetDatasourceId }).then((res) => {
          if (res.data.code === 200) {
            this.wTbList = res.data.data
          }
        })
      },
      wDsChange(e) {
        // 清空
        this.writerForm.tables = []
  
        this.wDsList.find((item) => {
          if (item.id === e) {
            this.writerForm.sourceName = item.sourceName
            this.dataSource = item
          }
        })
        this.changeType(this.key)
        Bus.sourceId = e
        // this.$emit('selectDataSource', this.dataSource)
      },
      wHandleCheckAllChange(val) {
        this.writerForm.columns = val ? this.wColumnList : []
        this.writerForm.isIndeterminate = false
      },
      wHandleCheckedChange(value) {
        const checkedCount = value.length
        this.writerForm.checkAll = checkedCount === this.wColumnList.length
        this.writerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.wColumnList.length
      },
      getData() {
        if (Bus.sourceId) {
          this.writerForm.sourceId = Bus.SourceId
        }
        return this.writerForm
      },
      getReaderData() {
        return this.$parent.getReaderData()
      },
      getTableName() {
        return this.fromTableName
      },
      handleRowClick(row) {
        // 在 @row-click 事件中获取行号
        this.nowIndex = this.selColumnList.indexOf(row)
        console.log('点击的行号：', this.nowIndex)
      },
    },
  }
  </script>
  
  